/*
 * exti.c
 *
 *  Created on: 2024年6月28日
 *      Author: 23206
 */

#include "exti.h"
#include <stdio.h>

//PB5
void EXTI_Config(void)
{
	//1.1中断的IO配置

	RCC->AHB1ENR |=  1<<1;      //GPIOB打开
	GPIOB->MODER &= ~(0x3<<5*2);//输入模式
	GPIOB->PUPDR &= ~(0x3<<5*2);//无上下拉

	KEY_Config();

	//1.2中断参数配置
	//1.APB2的时钟使能寄存器第14位
	RCC->APB2ENR |= 1<<14;
    //PX.Y  根据Y  Y= 0 1 2 3 选数组0 Y = 4 5 6 7 选数组1 Y = 8 9 10 11 选数组2 Y = 12 13 14 15 数组3
	SYSCFG->EXTICR[0]&= ~(0xF<<4*0);//PA0
	SYSCFG->EXTICR[0]|=  (0x0<<4*0);//0000

    SYSCFG->EXTICR[0]&= ~(0xF<<4*2);//PA2
    SYSCFG->EXTICR[0]|=  (0x4<<4*2);//A   BCDE PE2  //X=A 装0 X=B 装1 X=C 装2 X=D 装3 X=E 装4

	SYSCFG->EXTICR[0]&= ~(0xF<<4*3);//PA3
	SYSCFG->EXTICR[0]|=  (0x4<<4*3);//A   BCDE PE3

	SYSCFG->EXTICR[1]&= ~(0xF<<4*0);//PA4
	SYSCFG->EXTICR[1]|=  (0x4<<4*0);//A   BCDE PE4

	SYSCFG->EXTICR[1]&= ~(0xF<<4*1);//PA5
	SYSCFG->EXTICR[1]|=  (0x1<<4*1);//0001 选PB5


	//谁以什么样的方式触发中断
	EXTI->IMR |= (1<<5);//允许中断
	EXTI->FTSR|= 1<<5;//下降沿允许
	EXTI->RTSR|= 1<<5;//上升沿允许

	EXTI->IMR |= (1<<0)|(1<<2)|(1<<3)|(1<<4);
	EXTI->RTSR|= (1<<2)|(1<<3)|(1<<4); //上升沿允许
	EXTI->FTSR|= (1<<0);               //下降沿允许

	//谁触发中断被允许
	NVIC_SetPriority(EXTI9_5_IRQn, NVIC_EncodePriority(7-2,1,3));
	NVIC_EnableIRQ(EXTI9_5_IRQn); //使能某个编号的中断

	NVIC_SetPriority(EXTI0_IRQn, NVIC_EncodePriority(7-2,1,3));
	NVIC_EnableIRQ(EXTI0_IRQn); //使能某个编号的中断

	NVIC_SetPriority(EXTI2_IRQn, NVIC_EncodePriority(7-2,1,3));
	NVIC_EnableIRQ(EXTI2_IRQn); //使能某个编号的中断

	NVIC_SetPriority(EXTI3_IRQn, NVIC_EncodePriority(7-2,1,3));
	NVIC_EnableIRQ(EXTI3_IRQn); //使能某个编号的中断

	NVIC_SetPriority(EXTI4_IRQn, NVIC_EncodePriority(7-2,1,3));
	NVIC_EnableIRQ(EXTI4_IRQn); //使能某个编号的中断

}

//懂？
void EXTI9_5_IRQHandler(void)
{
	//判断标志位  清除标志位
	if(EXTI->PR & 1<<5)
	{
		EXTI->PR |= 1<<5;//写第5位为1  清除当前标志
		if(GPIOB->IDR&1<<5)
		{
			printf("UP\r\n");
		}
		else
		{
			printf("DOWN\r\n");
		}
	}

}
//PA0的中断服务函数 下降沿
void EXTI0_IRQHandler(void)
{
	if(EXTI->PR & 1<<0)
	{
		EXTI->PR |= 1<<0;//写第0位为1  清除当前标志
		printf("1 UP\r\n");
	}

}

//PE2的中断服务函数 上升沿
void EXTI2_IRQHandler(void)
{
	if(EXTI->PR & 1<<2)
	{
		EXTI->PR |= 1<<2;//写第5位为21  清除当前标志
		printf("2 DOWN\r\n");
	}

}
uint8_t A_Flag = 0;
uint8_t B_Flag = 0;
uint8_t C_Flag = 0;
//PE3的中断服务函数 上升沿
//PE4的中断服务函数 上升沿
void EXTI3_IRQHandler(void)
{
	if(EXTI->PR & 1<<3)
	{
		EXTI->PR |= 1<<3;//写第3位为21  清除当前标志
		printf("3 DOWN\r\n");
		A_Flag = 1;//A被触发
		C_Flag = 1;
	}
}
void EXTI4_IRQHandler(void)
{
	if(EXTI->PR & 1<<4)
	{
		EXTI->PR |= 1<<4;//写第4位为21  清除当前标志
		printf("4 DOWN\r\n");
		B_Flag = 1;
		C_Flag = 2;
	}
}
